package ael.imarkket;

import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ael.imarkket.Library.ConnectionChecking;
import ael.imarkket.Library.Constantes;
import ael.imarkket.Library.HttpPostGet;
import ael.imarkket.Library.HttpPostGet.RequestMethod;
import ael.imarkket.Library.Logging;
import ael.imarkket.Library.Preferencing;
import ael.imarkket.Library.StatusApp;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

/* EJEMPLO 

 [APP    ] JSON: 
 | {
 | 	"ListaDeLaCompra": [
 | 		{
 | 			"ID": 1,
 | 			"DESCRIPTION": "Dieta",
 | 			"CREATED": "2013-11-13 03:20:26",
 | 			"UPDATED": "2013-11-13 03:20:26",
 | 			"SHARED": "0"
 | 		},
 | 		{
 | 			"ID": 2,
 | 			"DESCRIPTION": "Fiesta",
 | 			"CREATED": "2013-11-13 05:20:26",
 | 			"UPDATED": "2013-11-13 05:20:26",
 | 			"SHARED": "1"
 | 		}
 | 	],
 | 	"Total": 2
 | }

 */

public class ShoppingList extends ListActivity {

	protected ShoppinListTask	_Task						= null;
	static Context				context;
	static InputStream			is							= null;
	String						ResponseHTTP				= "";

	Integer						ResultTask					= null;
	ListView					lv;

	final private static int	DIALOG_SHOPPING_LIST_ADD	= 1;
	private String				NEW_LIST_SHARED				= "";
	private String				NEW_LIST_NAME				= "";

	Integer						ItemSelected				= -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shopping_list);

		// Inicializamos la tarea
		this.ResultTask = null;

		// Creamos la lista de la compra en base al array
		LanzarShoppinListTask(context, getString(R.string.str_Load_Listas), getString(R.string.STR_OPERATION_LOAD_LISTAS));
	}

	/*
	 * Creamos la lista de la compra
	 */

	public void CrearListaDeLaCompra(String pObjetoSJON) {

		// En la variable ObjetoSJON viene el JSON para tratarlo
		// Ya viene devuelto como string ResponseHTTP por el método en AppHttpPostGet.executeRequest --> convertStreamToString
		try {
			// Cargamos el objeto JSON
			// Es un objeto json porque empieza por {}, si empezase por [] sería un array JSON
			JSONObject JSONObject = new JSONObject(pObjetoSJON);

			// si no está vacío
			if (JSONObject != null) {
				// Array de Listas de la Compra
				JSONArray JSONArrayLista = JSONObject.getJSONArray("ListaDeLaCompra");

				// Obtenemos el total del array
				int TotalArray = JSONArrayLista.length();

				// Obtenemos el total de JSON
				int TotalJSON = JSONObject.getInt("Total");

				// Si los 2 coinciden
				if (TotalArray == TotalJSON) {

					// Matriz Bidimensional JSON
					// Matriz de n Elementos y 5 columnas, el total de características de cada lista de la compra
					String[][] MatrizBidimensionalJSON = new String[TotalJSON][6];

					// Recorremos el array de Lista de la Compra
					for (int i = 0; i < JSONArrayLista.length(); i++) {

						// Por cada elemento de la lista creamos su correspondiente OBJETO JSON
						JSONObject JSONObjectElement = new JSONObject(JSONArrayLista.get(i).toString());

						// Sacamos cada propiedad
						String JSON_OBJECT_ID = JSONObjectElement.getString("ID");
						String JSON_OBJECT_DESCRIPTION = JSONObjectElement.getString("DESCRIPTION");
						String JSON_OBJECT_CREATED = JSONObjectElement.getString("CREATED");
						String JSON_OBJECT_UPDATED = JSONObjectElement.getString("UPDATED");
						String JSON_OBJECT_SHARED = JSONObjectElement.getString("SHARED");
						String JSON_OBJECT_COUNT = JSONObjectElement.getString("COUNT");

						// Extremos los datos del JSON
						MatrizBidimensionalJSON[i][0] = JSON_OBJECT_ID;
						MatrizBidimensionalJSON[i][1] = JSON_OBJECT_DESCRIPTION;
						MatrizBidimensionalJSON[i][2] = JSON_OBJECT_CREATED;
						MatrizBidimensionalJSON[i][3] = JSON_OBJECT_UPDATED;
						MatrizBidimensionalJSON[i][4] = JSON_OBJECT_SHARED;
						MatrizBidimensionalJSON[i][5] = JSON_OBJECT_COUNT;

						// AppLog.getInstance().log(AppLog.LOG_INFO,"****i: " + JSONArrayLista.get(i).toString());
						Logging.getInstance().log(
								Logging.LOG_INFO,
								"i: [ " + JSON_OBJECT_ID + " - " + JSON_OBJECT_DESCRIPTION + " - " + JSON_OBJECT_CREATED + " - " + JSON_OBJECT_UPDATED + " - " + JSON_OBJECT_SHARED
										+ " ] ");
					}
					setListAdapter(new ShoppingListAdapter(this, TotalJSON, MatrizBidimensionalJSON));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
		ItemSelected = position;

		// Lanzamos la actividad de la lista de elementos de la compra
		Intent mainIntent = new Intent().setClass(ShoppingList.this, ProductShoppingList.class);
		startActivity(mainIntent);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// populateMenu(menu);
		// return (super.onCreateOptionsMenu(menu));

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_shopping_list, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		applyMenuChoice(item);

		return (applyMenuChoice(item) || super.onOptionsItemSelected(item));
	}

	@SuppressWarnings("deprecation")
	private boolean applyMenuChoice(MenuItem item) {

		switch (item.getItemId()) {
			case R.id.menu_add:
				// Toast.makeText(ShoppingList.this, ItemSelected.toString(), Toast.LENGTH_LONG).show();
				showDialog(DIALOG_SHOPPING_LIST_ADD);
				return (true);
			case R.id.menu_action_exit:
				attemptExit();
				return true;
			case R.id.menu_action_logout:
				// Al cerrar la sesión desactivamos la preferencia de AUTO_LOGIN
				// Restauramos el email por defecto en las preferencias
				context = getApplicationContext();
				Preferencing appPrefs = new Preferencing(context);
				appPrefs.setAutoLogin(false);

				// Cerramos con la tarea asíncrona
				LanzarShoppinListTask(context, getString(R.string.str_logout_session), getString(R.string.STR_OPERATION_LOGOUT));
				return true;
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		AlertDialog dialogDetails = null;
		// final String[] items = { "Compartir" };

		switch (id) {
			case DIALOG_SHOPPING_LIST_ADD:
				LayoutInflater inflater = LayoutInflater.from(this);
				View dialogview = inflater.inflate(R.layout.shoppinglistdialog, null);

				AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
				// Título de la ventana
				dialogbuilder.setTitle(R.string.str_new_list);
				// Nombre de la lista
				dialogbuilder.setView(dialogview);

				dialogDetails = dialogbuilder.create();

				break;
		}

		return dialogDetails;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {

		switch (id) {
			case DIALOG_SHOPPING_LIST_ADD:
				final AlertDialog alertDialog = (AlertDialog) dialog;
				Button okbutton = (Button) alertDialog.findViewById(R.id.btn_ok);
				Button cancelbutton = (Button) alertDialog.findViewById(R.id.btn_cancel);
				final EditText NameShoppingList = (EditText) alertDialog.findViewById(R.id.id_list_name);
				final CheckBox SharedList = (CheckBox) alertDialog.findViewById(R.id.id_list_shared);

				okbutton.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// Cancel por defecto
						boolean cancel = false;
						View focusView = null;

						// Reset errors.
						NameShoppingList.setError(null);
						SharedList.setError(null);

						// Store values at the time of the login attempt.
						String mName = NameShoppingList.getText().toString();
						Boolean nShared = SharedList.isChecked();

						// Check for a valid password.
						if (TextUtils.isEmpty(mName)) {
							NameShoppingList.setError(getString(R.string.error_field_required));
							focusView = NameShoppingList;
							cancel = true;
						}

						if (cancel) {
							// There was an error; don't attempt login and focus the first
							// form field with an error.
							focusView.requestFocus();
							Logging.getInstance().log(Logging.LOG_INFO, "Cancelado");
						} else {
							// Show a progress spinner, and kick off a background task to
							// perform the user login attempt.
							alertDialog.dismiss();
							NEW_LIST_SHARED = nShared.toString();
							NEW_LIST_NAME = mName;
							LanzarShoppinListTask(context, getString(R.string.str_list_add), getString(R.string.STR_OPERATION_LIST_ADD));
						}
					}
				});

				cancelbutton.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});
				break;
		}
	}

	private void LanzarShoppinListTask(Context context, String str_modo, String modo) {
		// Lanzamos la tarea asÃ­ncrona

		// Lanzar la ejecuciÃ³n solo una vez
		if (_Task != null && _Task.getStatus() != AsyncTask.Status.FINISHED) {
			Logging.getInstance().log(Logging.LOG_INFO, "Cancelando InitTask (si existe antes)");
			_Task.cancel(true);
		}

		// ///////// TAREA ASINCRONA
		_Task = new ShoppinListTask(ShoppingList.this, str_modo, modo);
		_Task.execute(this);

		try {
			this.ResultTask = _Task.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Attempts to exit .
	 */

	public void attemptExit() {

		// 1. Instantiate an AlertDialog.Builder with its constructor
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		// 2. Chain together various setter methods to set the dialog
		// characteristics
		builder.setMessage(R.string.action_sign_exit_text).setTitle(R.string.action_sign_exit);

		builder.setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User clicked OK button
				// Salimos de la herramienta
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit) + "OK");
				finish();
			}
		});
		builder.setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User cancelled the dialog
				// No hacemos nada
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit) + "FAIL");
			}
		});

		// 3. Get the AlertDialog from create()
		AlertDialog dialog = builder.create();

		// Mostramos el cuadro de dialogo
		dialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit));
			attemptExit();
			// Si el listener devuelve true, significa que el evento esta
			// procesado, y nadie debe hacer nada mas
			return true;
		}
		// para las demas cosas, se reenvia el evento al listener habitual
		return super.onKeyDown(keyCode, event);
	}

	protected class ShoppinListTask extends AsyncTask<Context, Integer, Integer> {

		Context						context;
		String						str_mesg;
		String						modo;
		ProgressDialog				progress;

		private static final int	NETWORK_THINKING							= 0;

		private static final int	NETWORK_OK									= 1;
		private static final int	NETWORK_FAIL								= 2;
		private static final int	NETWORK_WIFI								= 3;
		private static final int	NETWORK_MOBILE								= 4;
		private static final int	NETWORK_UNKNOWN								= 5;

		private static final int	CONNECTING_TO_SERVER						= 6;
		private static final int	CONNECTING_TO_SERVER_OK						= 7;
		private static final int	CONNECTING_TO_SERVER_ERROR					= 8;
		private static final int	CONNECTING_TO_SERVER_FINISH					= 9;
		private static final int	HTTP_CONNECTING_ERROR						= 10;
		private static final int	CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT	= 11;
		private static final int	CONNECTING_TO_SERVER_ERROR_PROTOCOL			= 12;

		public ShoppinListTask(Context context, String str_modo, String modo) {
			Logging.getInstance().log(Logging.LOG_INFO, "CONSTRUCTOR");
			this.context = context;
			this.str_mesg = str_modo;
			this.modo = modo;
		}

		// -- run intensive processes here
		// -- notice that the datatype of the first param in the class
		// definition matches the param passed to this method
		// -- and that the datatype of the last param in the class definition
		// matches the return type of this mehtod
		@Override
		protected Integer doInBackground(Context... params) {
			// -- on every iteration
			// -- runs a while loop that causes the thread to sleep for 50 milliseconds
			// -- publishes the progress - calls the onProgressUpdate handler defined below
			// -- and increments the counter variable i by one
			//
			// int i = 0; while (i <= 50) { try { Thread.sleep(50);
			// publishProgress(i); i++; } catch (Exception e) {
			// AppLog.getInstance().log( "[doInBackground]" + e.getMessage()); }
			// }
			//
			// Variable de retorno de la tarea asï¿½ncrona
			// 1 si hay error
			// 0 si ha ido todo bien
			Integer return_code = 1;

			publishProgress(NETWORK_THINKING);

			// Comprobamos si hay conexion
			if (StatusApp.getInstance(this.context).isOnline(context)) {
				publishProgress(NETWORK_OK);
				Logging.getInstance().log(Logging.LOG_INFO, StatusApp.getInstance(this.context).getTypeStatus());

				// Comprobamos si es por wifi o mobil
				if ((ConnectionChecking.getInstance(this.context).CheckWIFI()) || (ConnectionChecking.getInstance(this.context).CheckMOBILE())) {
					if (ConnectionChecking.getInstance(this.context).CheckWIFI()) {
						publishProgress(NETWORK_WIFI);
					} else if (ConnectionChecking.getInstance(this.context).CheckMOBILE()) {
						publishProgress(NETWORK_MOBILE);
					}
					// Si llega aquÃ­ todo va bien lanzamos la conexion http
					// ****************************************************
					try {
						// Conexion http
						// Probamos la conexion contra el servidor para ver si
						// hay respuesta si nos devuelve 0 estï¿½ ok si nos
						// devuelve otra cosa distinta de 0
						// no hay conexiï¿½n con el servidor.

						publishProgress(CONNECTING_TO_SERVER);

						Constantes Constantes = new Constantes();
						HttpPostGet client = new HttpPostGet(Constantes.getAPI_PROTOCOL_HTTP() + Constantes.getAPI_IP(Constantes.getModoIP()) + Constantes.getAPI_URL_BASE()
								+ Constantes.getAPI_FILE(), Constantes.getAPI_CODIFICACION(), Constantes.getID_APP());

						//
						// Creamos el array con los datos de la operacion,
						// username y password
						//

						ArrayList<NameValuePair> OpeUserPassw = new ArrayList<NameValuePair>();
						OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_OPERATION), this.modo));
						// Extraemos de las preferencias el usuario actual
						// Restauramos el email por defecto en las preferencias
						Context context = getApplicationContext();
						Preferencing appPrefs = new Preferencing(context);
						OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_USERNAME), appPrefs.getUsername(false)));
						OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_PASSWORD), appPrefs.getPassword(false)));

						// Si la operación es la de new_list se pasa este parámetro sino NO
						if (this.modo == getString(R.string.STR_OPERATION_LIST_ADD)) {
							OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_NEW_LIST_SHARED), NEW_LIST_SHARED));
							OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_NEW_LIST_NAME), NEW_LIST_NAME));
						}

						try {
							// Le pasamos el array con las operaciones y los
							// datos del usuario
							// La variable HTTP_USER_AGENT_APP_ANDROID es para
							// que el php que detecta el movil lo ponga como
							// APP_MOVIL
							client.Execute(RequestMethod.POST, getString(R.string.HTTP_USER_AGENT_APP_ANDROID), OpeUserPassw, this.context, this.modo);
							publishProgress(CONNECTING_TO_SERVER_OK);
						} catch (SocketTimeoutException e) {
							publishProgress(CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT);
							Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
						} catch (ClientProtocolException e) {
							publishProgress(CONNECTING_TO_SERVER_ERROR_PROTOCOL);
							Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
						} catch (Exception e) {
							Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
							publishProgress(CONNECTING_TO_SERVER_ERROR);
						}

						// Guardamos la respuesta de la peticiï¿½n HTTP.
						ResponseHTTP = client.getResponse();
						ResponseHTTP = ResponseHTTP.replaceAll("[\n\r]", "");
						ResponseHTTP = ResponseHTTP.trim();
						int responseCode = client.getResponseCode();
						Logging.getInstance().log(Logging.LOG_INFO, "ResponseHTTP:  " + ResponseHTTP);
						Logging.getInstance().log(Logging.LOG_INFO, "ResponseCODE:  " + responseCode);
						// 200
						if (responseCode == HttpStatus.SC_OK) {
							publishProgress(CONNECTING_TO_SERVER_FINISH);
							// Esta variable es la que devuelve el procedimiento
							// cuando todo acaba bien.
							// Es la que procesará el procedimiento PostExecuted
							// con el nombre "resul"
							// En este caso "resul" devolverá en postexecuted un
							// 0
							return_code = 0;
						} else {
							// Hago esto para que si hay algï¿½n error me lo
							// devuelve en un Toast
							publishProgress(responseCode);
						}

						// Fin conexion http
					} catch (Exception e) {
						Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
						publishProgress(HTTP_CONNECTING_ERROR);
					}
					// ****************************************************
				} else {
					// ni wifi ni mobile
					publishProgress(NETWORK_UNKNOWN);
				}
			} else {
				// sin conexion
				publishProgress(NETWORK_FAIL);
			}
			// Variable de retorno de la tarea asï¿½ncrona
			// 1 -> si devuelve 1 es que no se ha realizado correctamente la
			// conexiï¿½n. Despuï¿½s tenemos que procesar el resultado json.
			return return_code;
		}

		// -- gets called just before thread begins
		@Override
		protected void onPreExecute() {
			Logging.getInstance().log(Logging.LOG_INFO, "INICIALIZANDO");
			super.onPreExecute();

			progress = new ProgressDialog(context);
			progress.setMessage(str_mesg);
			// set other progressbar attributes
			progress.show();
		}

		// -- called from the publish progress
		// -- notice that the datatype of the second param gets passed to this
		// method
		@Override
		protected void onProgressUpdate(Integer... code) {
			super.onProgressUpdate(code);

			String mensaje = "";
			switch (code[0]) {
				case NETWORK_OK:
					mensaje = getString(R.string.AppCheckConnection_ok);
					break;
				case NETWORK_FAIL:
					mensaje = getString(R.string.AppCheckConnection_fail);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case NETWORK_WIFI:
					mensaje = getString(R.string.AppCheckConnection_ok) + " " + getString(R.string.AppCheckConnection_wifi_connection);
					break;
				case NETWORK_MOBILE:
					mensaje = getString(R.string.AppCheckConnection_ok) + " " + getString(R.string.AppCheckConnection_mobile_connection);
					break;
				case NETWORK_UNKNOWN:
					mensaje = getString(R.string.AppCheckConnection_ok) + " " + getString(R.string.AppCheckConnection_unknown);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER:
					mensaje = getString(R.string.Connect_to_server);
					break;
				case CONNECTING_TO_SERVER_OK:
					mensaje = getString(R.string.Connect_to_server) + " " + getString(R.string.Connect_to_server_ok);
					break;
				case CONNECTING_TO_SERVER_ERROR:
					mensaje = getString(R.string.Connect_to_server) + " " + getString(R.string.Connect_to_server_error_refused);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER_FINISH:
					// mensaje = getString(R.string.Connect_to_server) + " " +
					// getString(R.string.Connect_to_server_ok);
					// Toast.makeText(getApplicationContext(),
					// getString(R.string.Http_Connect_Finish),
					// Toast.LENGTH_LONG).show();
					break;
				case HTTP_CONNECTING_ERROR:
					mensaje = getString(R.string.Http_Connect_Error);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT:
					mensaje = getString(R.string.Connect_to_server_error_sockettimeout);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER_ERROR_PROTOCOL:
					mensaje = getString(R.string.Connect_to_server_error_protocol);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case NETWORK_THINKING:
					mensaje = getString(R.string.AppCheckConnection_thinking);
					break;
				default:
					// Aquï¿½ se va cuando hay mensajes 200, 300, 400, ... 500 ....
					mensaje = getString(R.string.Connect_to_server) + " - ErrorCode:" + code[0].toString();
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
			}
			Logging.getInstance().log(Logging.LOG_INFO, "PROGRESS: (" + code[0].toString() + ")" + mensaje);
			progress.setMessage(mensaje);
			// Hacemos una pausa pequeï¿½a
			// SystemClock.sleep(100);

		}

		// -- called if the cancel button is pressed
		@Override
		protected void onCancelled() {
			super.onCancelled();
			Logging.getInstance().log(Logging.LOG_INFO, "CANCELLED");
		}

		// -- called as soon as doInBackground method completes
		// -- notice that the third param gets passed to this method
		@Override
		protected void onPostExecute(Integer result) {

			// El valor de esta variable viene del procedimiento
			// doBackgroundtStreamToString(instream); (return_code)
			// result = 1 error
			// result = 0 ok
			Logging.getInstance().log(Logging.LOG_INFO, "1Result:  " + result + " ResponseHTTP: " + ResponseHTTP);

			// La conexion se ha realiado con éxito ahora hay que ver si el
			// login se ha hecho bien.
			if (result == 0) {
				// Comprobamos el json
				// En ResponseHTTP tenemos el JSON recibido de la app PHP
				if ((ResponseHTTP == "") || (ResponseHTTP == null)) {
					Toast.makeText(getApplicationContext(), getString(R.string.ERROR) + ':' + this.modo, Toast.LENGTH_LONG).show();
					Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.ERROR) + ':' + this.modo + ' ' + "2Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
				} else {
					if (this.modo == getString(R.string.STR_OPERATION_LOGOUT)) {
						// Cerrar sesion
						Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.str_logout_session));
						Intent mainIntent = new Intent().setClass(ShoppingList.this, Login.class);
						startActivity(mainIntent);
						finish();
					} else if (this.modo == getString(R.string.STR_OPERATION_LOAD_LISTAS)) {
						// Todo correcto se pasa el objeto JSON al proc que creará la lista.

						// Cargamos la lista de la Compra pasándole el JSON
						CrearListaDeLaCompra(ResponseHTTP);
						Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.str_Load_Listas));

					} else if (this.modo == getString(R.string.STR_OPERATION_LIST_ADD)) {
						// Creación correcta
						if (ResponseHTTP.equals("0")) {
							Toast.makeText(getApplicationContext(), "Creación correcta.", Toast.LENGTH_LONG).show();
							LanzarShoppinListTask(context, getString(R.string.str_Load_Listas), getString(R.string.STR_OPERATION_LOAD_LISTAS));
							// Lista duplicada
						} else if ((ResponseHTTP.equals("1")) || (ResponseHTTP.equals("2")) || (ResponseHTTP.equals("3"))) {
							Toast.makeText(getApplicationContext(), "Lista duplicada", Toast.LENGTH_LONG).show();
						}
					}
				}

			} else if (result == 1) {
				// En este caso que la variable result ha devuelto 1, nos da
				// igual el valor que ha devuelto ResponseHTTP, ya que
				// ahí debería haber un array con la lista de la compra.
				Toast.makeText(getApplicationContext(), getString(R.string.ERROR) + ':' + this.modo + ' ', Toast.LENGTH_LONG).show();
				Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.ERROR) + ':' + this.modo + ' ' + " 7Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
			} else {
				// En este caso que la variable result ha devuelto otra cosa,
				// nos da igual el valor que ha devuelto ResponseHTTP, ya que
				// ahí debería haber un array con la lista de la compra.
				Toast.makeText(getApplicationContext(), getString(R.string.ERROR) + ':' + this.modo + ' ' + result.toString(), Toast.LENGTH_LONG).show();
				Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.ERROR) + ':' + this.modo + ' ' + " 8Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
			}

			progress.dismiss();
		}
	}

	/*
	 * FIN TAREA LOGIN ASINCRONA
	 */

}